package com.lilingguo.easyserver.config;

import com.lilingguo.easyserver.job.HeartBeatJob;
import com.lilingguo.easyserver.job.UpdateServiceInfoJob;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

/**
 * 定时任务配置类
 * 1、配置多线程
 * 2、增加错误预警
 * 3、配置定时任务
 *
 * @Author: 黎铃果
 * @Date: 2020/05/28 16:28
 */
@Log4j2
@Configuration
public class ClientSchedulingConfigure implements SchedulingConfigurer {

    @Autowired
    private ClientProperties clientProperties;

    @Autowired
    private UpdateServiceInfoJob updateServiceInfoJob;
    @Autowired
    private HeartBeatJob heartBeatJob;

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        ThreadPoolTaskScheduler handler = new ThreadPoolTaskScheduler();
        handler.setPoolSize(10);
        handler.setThreadNamePrefix("easyserver-thread-");
        handler.setAwaitTerminationSeconds(60);
        handler.setErrorHandler(t -> log.error("Bad scheduled task : " + t));
        // init
        handler.initialize();

        // set schedules
        handler.scheduleAtFixedRate(updateServiceInfoJob, clientProperties.getUpdateRate());
        handler.scheduleAtFixedRate(heartBeatJob, clientProperties.getHealthTickRate());

        scheduledTaskRegistrar.setScheduler(handler);
    }
}
